import React, {useState, useEffect} from 'react';
import {MapContainer, TileLayer, useMap, ZoomControl} from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import 'leaflet.markercluster/dist/MarkerCluster.css';
import 'leaflet.markercluster/dist/MarkerCluster.Default.css';
import 'leaflet.markercluster';
import {Select} from 'antd'; // 引入 Ant Design 的 Select 组件
import {useTranslation} from 'react-i18next';

import markerIcon2x from 'leaflet/dist/images/marker-icon-2x.png';
import markerShadow from 'leaflet/dist/images/marker-shadow.png';
import styles from "@src/views/Price/styles.module.less";
import request from "@src/services/request";


const {Option} = Select;

delete L.Icon.Default.prototype._getIconUrl;

L.Icon.Default.mergeOptions({
    iconRetinaUrl: markerIcon2x,
    iconUrl: "/img/map-marker.png",
    shadowUrl: markerShadow,
});

function MarkerCluster({markers}) {
    const map = useMap();

    useEffect(() => {
        const markerClusterGroup = L.markerClusterGroup();

        if (markers.length > 0) {
            markers.forEach(marker => {
                const leafletMarker = L.marker([marker.lat, marker.lng])
                    .bindPopup(`<div style="height: 50px; width:100%; background: url('https://portal.dcconnectglobal.com/site-picture/${marker.siteId}') no-repeat scroll center; background-size: contain;">
            </div><h2 style="font-size: 24px">${marker.name}</h2><br><div>${marker.addr}<div style="display: flex; gap: 4px; flex-wrap: wrap; margin-top: 10px;">
                ${marker.isSdn ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">SDN</span>` : ''}   
                ${marker.isEthernet ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">Ethernet</span>` : ''}   
                ${marker.isAli ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">ALI</span>` : ''}   
                ${marker.isAws ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">AWS</span>` : ''}   
                ${marker.isAzure ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">Azure</span>` : ''}   
                ${marker.isBaidu ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">Baidu</span>` : ''}   
                ${marker.isColocation ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">Colocation</span>` : ''}   
                ${marker.isGcp ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">Gcp</span>` : ''}   
                ${marker.isHuawei ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">Huawei</span>` : ''}   
                ${marker.isJDCloud ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">JDCloud</span>` : ''}   
                ${marker.isKingsoft ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">KingSoft</span>` : ''}   
                ${marker.isNutanixXi ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">NutanixXi</span>` : ''}   
                ${marker.isOfficeBldg ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">OfficeBldg</span>` : ''}   
                ${marker.isOracle ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">Oracle</span>` : ''}   
                ${marker.isQing ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">Qing</span>` : ''}   
                ${marker.isSalesforce ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">SalesForce</span>` : ''}   
                ${marker.isTencent ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">Tencent</span>` : ''}   
                ${marker.isUcloud ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">Ucloud</span>` : ''}   
                ${marker.isVpn ? `<span style="background-color: #7d68ef; color: white; padding: 4px 8px; border-radius: 4px;">Vpn</span>` : ''}   
            </div>`);
                markerClusterGroup.addLayer(leafletMarker);
            });
        }


        map.addLayer(markerClusterGroup);

        return () => {
            map.removeLayer(markerClusterGroup);
        };
    }, [map, markers]);

    return null;
}

function MapWithSidebar({markers, listPop}) {
    const {t} = useTranslation();
    const map = useMap();
    const [selectOpen, setSelectOpen] = useState(false);

    const handleMarkerChange = (value) => {
        const selectedMarker = markers.find(marker => marker.value == value);
        if (selectedMarker && map) {
            map.setView([selectedMarker.lat, selectedMarker.lng], 13); // 移动到选中的标记
        }
    };

    const handleSelect = value => {
        setTimeout(() => {
            setSelectOpen(false);
        }, 0);
    };

    return (
        <div className={styles.dc_select_div}>
            <div className={styles.div_1}>
                <Select
                    showSearch
                    className={styles.select}
                    placeholder={t('Please select source')}
                    optionFilterProp="children"
                    filterOption={(input, option) =>
                        (option?.desc?.toString().toLowerCase() ?? '').includes(input.toLowerCase()) ||
                        (option?.label?.toString().toLowerCase() ?? '').includes(input.toLowerCase())
                    }
                    filterSort={(optionA, optionB) =>
                        (optionA?.desc ?? '').toLowerCase().localeCompare((optionB?.desc ?? '').toLowerCase())
                    }
                    options={listPop}
                    open={selectOpen}
                    onDropdownVisibleChange={setSelectOpen}
                    onSelect={handleSelect}
                    onChange={handleMarkerChange}
                    listHeight={'60vh'}
                />
            </div>
            <div style={{flex: 1, height: '100%'}}>
                <TileLayer
                    attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                />
                <MarkerCluster markers={markers}/> {/* 保持标记聚合 */}
            </div>
        </div>
    );
}

function DataCenter() {
    const [markers, setMarkers] = useState([]);
    const [listPop, setListPop] = useState([]);

    useEffect(() => {
        const getDataList = async () => {
            try {
                const response = await request({
                    url: '/price/listDataCenter',
                    method: 'get',
                    data: {}
                });
                setMarkers(response);

            } catch (error) {
                console.error("Error fetching data center list: ", error);
            }
        };
        getDataList();
    }, []);


    const getListPop = async () => {
        try {
            const response = await request({
                url: '/price/listPop',
                method: 'get',
                data: {}
            });
            const formattedOptions = response.map(item => ({
                label: `${item.label}`, // 使用 label 和 desc 组合展示
                options: item.value.map(v => ({
                    label: (
                        <>
                            {v.label} <br/>
                            <span className={styles.subtext}> {v.desc} </span>
                        </>
                    ),
                    desc: v.label,
                    value: v.value // 使用你的实际字段名称替换
                })),
            }));
            setListPop(formattedOptions);
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };

    useEffect(() => {
        getListPop();
    }, []);

    return (
        <MapContainer
            center={[51.505, -0.09]}
            zoom={3}
            style={{height: '100vh'}}
            zoomControl={false}
        >
            <ZoomControl position="bottomright"/>
            <MapWithSidebar markers={markers} listPop={listPop}/>
        </MapContainer>
    );
}

export default DataCenter;
